<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_CATEGORIES;
require_once LIBRARIES_ENTITIES_ARTICLES;
require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERFRONTEND;

class Controller {

    public function invoke() {

        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        $item = '';
        if (isset($_GET['item'])) {
            $item = $_GET['item'];
        }

        if ($view == 'categories') {

            $derectory = dirname(__FILE__);
            $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'category.html');

            // category alias
            $categoryAlias = $_GET['alias'];
//            echo $categoryAlias;
            $category = $this->getCategoryByAlias($categoryAlias);
            $articles = $this->getArticlesByCategoryAlias($categoryAlias);

            if ($category != null) {
                $xtemplate->assign('CATEGORY_TITLE', $category->getTitle());
                $xtemplate->assign('CATEGORY_ID', $category->getID());
                $xtemplate->assign('CATEGORY_ALIAS', $category->getAlias());
            }

            if ($articles != null) {
                // current page
                $currentPage = 1;
                if (isset($_GET["page"])) {
                    $currentPage = $_GET["page"];
                }

                $pager = PagerFrontEnd::getPagerData(count($articles), LINE_PER_PAGE, $currentPage);

                $index = 1;

                // loop each article
                foreach ($articles as $article) { 
                    if ($index > $pager->offset && $index <= $pager->limit) {
                        $xtemplate->assign('ARTICLE_ID', $article->getID());
                        $xtemplate->assign('ARTICLE_ALIAS', $article->getAlias());
                        $xtemplate->assign('ARTICLE_TITLE', $article->getTitle());
                        $xtemplate->assign('ARTICLE_DATE', $article->getModifiedDate());
                        $xtemplate->assign('ARTICLE_DESCRIPTION', $article->getDescription());

                          if($index % 3 ==0){
                             $xtemplate->assign('clearfix', '<div class="clearfix"></div>');
                        }else{
                            $xtemplate->assign('clearfix', '');
                        }   

                        // if image status is true
                        // show image
                        if ($article->getImageStatus() == 1) {
                            $xtemplate->assign('ARTICLE_IMAGE', $article->getImage());
                            $xtemplate->parse('main.article.article_image');
                        }
                        $xtemplate->parse('main.article');
                    }
                    $index++;
                }
                $xtemplate->assign('PAGING', $pager->paging);
                $xtemplate->assign('CURRENT_PAGE', $currentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo 'Dữ liệu đang cập nhật';
            }
        } else if ($view == 'articles') {

            $articleAlias = $_GET['alias'];
            $article = $this->getArticleByAlias($articleAlias);

            if ($article != null) {

                $derectory = dirname(__FILE__);
                $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'article.html');

                // category detail
                $xtemplate->assign('CATEGORY_ALIAS', $article->getCategory()->getAlias());
                $xtemplate->assign('CATEGORY_ID', $article->getCategory()->getID());
                $xtemplate->assign('CATEGORY_TITLE', $article->getCategory()->getTitle());

                // article detail
                $xtemplate->assign('ARTICLE_TITLE', $article->getTitle());
                $xtemplate->assign('ARTICLE_MODIFIED_DATE', $article->getModifiedDate());
                $xtemplate->assign('ARTICLE_CONTENT', $article->getContent());

                // article list of the same category
                $articlesOfTheSameCategory = $this->getArticlesOfTheSameCategory($article->getCategoryID(), $article->getOrder());

                // if not null
                // show article list of the same category
                if ($articlesOfTheSameCategory != null) {
                    foreach ($articlesOfTheSameCategory as $value) {
                        $xtemplate->assign('ARTICLE_ALIAS_OF_THE_SAME_CATEGORY', $value->getAlias());
                        $xtemplate->assign('ARTICLE_ID_OF_THE_SAME_CATEGORY', $value->getID());
                        $xtemplate->assign('ARTICLE_TITLE_OF_THE_SAME_CATEGORY', $value->getTitle());
                        $xtemplate->assign('ARTICLE_DATE_OF_THE_SAME_CATEGORY', $value->getModifiedDate());
                        $xtemplate->parse('main.article_list_of_the_same_category.article_of_the_same_category');
                    }
                    $xtemplate->parse('main.article_list_of_the_same_category');
                }

                $xtemplate->parse('main');
                $xtemplate->out('main');

                $this->increaseHitsByArticleID($article->getID());
            } else {
                echo 'không tồn tại dữ liệu';
            }
        } else {
            // neu khong co vie thi tro ve trang chu
            Utility::redirect('.');
        }
    }

    // tai danh sach article boi categoryID
    private function getArticlesByCategoryID($categoryID) {
        $db = new Database();
        try {
            $article = new Articles();
            $article->setCategoryID($categoryID);
            $result = $article->getListByCategoryID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    private function getCategoryByAlias($categoryAlias) {
        $db = new Database();
        try {

            // get a category by alias
            $category = new Categories();
            $category->setAlias($categoryAlias);
            $result = $category->getByAlias($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // get article list by category alias
    private function getArticlesByCategoryAlias($categoryAlias) {
        $db = new Database();
        try {

            // get a category by alias
            $category = new Categories();
            $category->setAlias($categoryAlias);
            $category = $category->getByAlias($db);

            if ($category != null) {
                // get article list by category id
                $article = new Articles();
                $article->setCategoryID($category->getID());
                $result = $article->getListByCategoryID($db);
                $db->submitChanges();
                return $result;
            } else {
                return null;
            }
        } catch (PDOException $exc) {
            echo 'lỗi tải danh sách bài viết: '.$exc->getMessage();
            $db->rollback();
        }
    }

    // tai chi tiet 1 bai viet boi alias
    private function getArticleByAlias($articleAlias) {
        $db = new Database();
        try {
            $article = new Articles();
            $article->setAlias($articleAlias);
            $result = $article->getByAlias($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // update hits of an article
    private function increaseHitsByArticleID($articleID) {
        $db = new Database();
        try {
            $article = new Articles();
            $article->setID($articleID);
            $result = $article->increaseHitsByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    /**
     * get article list of the same category but have smaller order
     * @param type $categoryID
     * @param type $order
     * @return type: article list     
     */
    private function getArticlesOfTheSameCategory($categoryID, $order) {
        $db = new Database();
        try {
            $article = new Articles();
            $article->setOrder($order);
            $article->setCategoryID($categoryID);
            $result = $article->getListOfTheSameCategory($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

}

?>
